package br.com.conhecimento.infra.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.conhecimento.model.Usuario;

/**
 * Filter responsavel pelo usuario sessao 
 * 
 * @author Luis Garcia
 * @since 27/04/2013
 */
public class SecuritySession implements Filter {

    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        if (!this.authorize(req)) {
            res.sendRedirect(req.getContextPath() + "/");
        } else {
            res.setHeader("Cache-Control", "no-store");
            res.setHeader("Pragma", "no-cache");
            res.setDateHeader("Expires", 0);
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException { }

    private boolean authorize(HttpServletRequest req) {

        boolean authorized = false;
        HttpSession session = req.getSession(false);

        if (session != null) {
            Usuario user = (Usuario) session.getAttribute("usuario");
            if (user != null && 
            	user.getLogin() != null && 
            	user.getLogin().length() != 0) {
                authorized = true;
            }
        }
        return authorized;
    }
}